extends CharacterBody2D


const SPEED = 200.0
var player = null
var hp = 3
var ack:int = 1
var is_player_in:bool = false # 触碰到玩家，进行攻击
@onready var attack_timer = $attack_timer
var attack_speed:float = 1.0
var exp = 3
const ITEM = preload("res://item/item.tscn")

func killed():
	GameMain.enemy_die(global_position)
	queue_free()

func hurt():
	hp -= player.hurt
	$AnimatedSprite2D.material.set_shader_parameter("flash_opacity",1)
	await get_tree().create_timer(0.1).timeout
	$AnimatedSprite2D.material.set_shader_parameter("flash_opacity",0)
	GameMain.enemy_hurt(global_position)
	if hp <=0:
		die()
	pass

func die():
	GameMain.enemy_die(global_position)
	player.cur_exp += exp
	player.update_info()
	spwan_item(global_position)
	if get_node("/root/main").enemies.has(self):
		get_node("/root/main").enemies.erase(self)
	queue_free()
	pass
	
func attack():
	if is_player_in:
		player.flash()
		player.cur_hp -= ack
		player.update_info()
		attack_timer.start()
	else:
		attack_timer.stop()
	pass

func spwan_item(pos:Vector2):
	var item = ITEM.instantiate()
	item.global_position = pos
	get_tree().root.add_child(item)

func _ready() -> void:
	attack_timer.wait_time = attack_speed
	player = get_tree().get_first_node_in_group("player")
	pass

func _physics_process(delta: float) -> void:
	velocity = global_position.direction_to(player.global_position) * SPEED
	move_and_slide()
	pass


func _on_body_area_body_entered(body):
	print("player in")
	is_player_in = true
	attack()
	pass # Replace with function body.


func _on_body_area_body_exited(body):
	print("player out")
	is_player_in = false
	pass # Replace with function body.


func _on_attack_timer_timeout():
	pass # Replace with function body.
